<script lang="ts" setup>
import { ref } from 'vue'
import { useUserAddress } from '@/stores/user-address'

const userAddress = useUserAddress()

const addressData = ref({
  user: '',
  telephone: '',
  dormitory: ''
})

// 表单校验规则
const rules = {
  user: {
    rules: [{
      required: true,
      errorMessage: '请输入姓名'
    }, {
      minLength: 2,
      maxLength: 10,
      errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符'
    }]
  },
  telephone: {
    rules: [{
      required: true,
      errorMessage: '请输入手机号'
    }, {
      pattern: /^1[3-9]\d{9}$/,
      errorMessage: '手机号格式不正确'
    }]
  },
  dormitory: {
    rules: [{
      required: true,
      errorMessage: '请输入宿舍信息'
    }]
  }
}

// 获取表单引用
const baseForm = ref()

// 点击修改数据
const onRevise = async () => {
  try {
    // 校验表单
    await baseForm.value.validate()

    // 校验通过后执行
    userAddress.updateAddress(addressData.value)
    // 返回上一页
    uni.navigateBack()
    // 显示修改成功提示
    uni.showToast({
      title: '修改成功',
      icon: 'success',
      duration: 1500
    })
  } catch (e) {
    console.log('表单校验失败:', e)
  }
}
</script>


<template>
<view class="address">
    <view class="address-input">
      <uni-forms ref="baseForm" :modelValue="addressData" :rules="rules">
        <uni-forms-item label="姓名" required name="user">
          <uni-easyinput class="uni-input" v-model="addressData.user" placeholder="联系人" />
        </uni-forms-item>
        <uni-forms-item label="电话" required name="telephone">
          <uni-easyinput class="uni-input" v-model="addressData.telephone" placeholder="电话" />
        </uni-forms-item>
        <uni-forms-item label="宿舍" required name="dormitory">
          <uni-easyinput class="uni-input" v-model="addressData.dormitory" placeholder="宿舍楼层门牌号" />
        </uni-forms-item>
      </uni-forms>
    </view>
    <button type="primary" @click="onRevise">确定</button>
  </view>
</template>


<style scoped lang="scss">
.address {
  margin-top: $uni-margin-top1;

  &-input {
    border-radius: $uni-border-radius;
    margin-bottom: 30rpx;
  }
}

:deep(.uni-easyinput__content-input) {
  padding: 15rpx ;
}
</style>